// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import store from '../../store'

import {AjaxPlugin, LoadingPlugin, ToastPlugin, AlertPlugin} from 'vux'
Vue.use(LoadingPlugin)

Vue.config.productionTip = false

document.addEventListener("deviceready", onDeviceReady, false);

// Cordova is ready
//
function onDeviceReady() {
	document.addEventListener("jpush.receiveRegistrationId", onJPushReceiveRegistrationId, false);
	cordova.plugins.backgroundMode.enable();
	getPermissions()
	if (cordova.platformId == 'android') {
		StatusBar.backgroundColorByHexString("#333");
	}
}

function getPermissions() {
	let permissions = cordova.plugins.permissions;

	permissions.requestPermission(permissions.CAMERA, success, error);

	function error() {
		console.warn('Camera permission is not turned on');
	}

	function success( status ) {
		if( !status.hasPermission ) error();
	}
}

function onJPushReceiveRegistrationId() {
	initiateUI();
}

function initiateUI() {
	try{
		window.JPush.init();
		window.JPush.setDebugMode(true);
		window.setTimeout(getRegistrationID, 1000);

		if (device.platform != "Android") {
			window.JPush.setApplicationIconBadgeNumber(0);
		}
	} catch (exception) {
		console.log('initiateUI: ' + exception);
	}
};

function getRegistrationID() {
	window.JPush.getRegistrationID(onGetRegistrationID);
};

function onGetRegistrationID() {
	try{
		console.log("JPushPlugin:registrationID is " + data);

		if (data.length == 0) {
			var t1 = window.setTimeout(getRegistrationID, 1000);
		}
	}catch (exception){
		console.log('onGetRegistrationID: ' + exception);
	}
};


Vue.axios.interceptors.request.use(
	function (config) {
		if (store.state.user.token) {
			config.headers.Authorization = `${store.state.user.token}`;
		}
		return config;
	},
	function (error) {
		// Do something with request error
		return Promise.reject(error);
	}
);

// 添加一个响应拦截器
Vue.axios.interceptors.response.use(function (response) {
		if(response.data.code=='1001'||response.data.code=='1002'){//具体的判断token失效的参数
			store.dispatch('deleteToken')
			store.dispatch('deleteUser')
			//sessionStorage.setItem("LoginUser",'{}')
			alert(response.data.msg);
			location.assign('/login/login.html')
		}else{
			return response
		}
	},
	function (error) {
		if (error.response) {
			switch (error.response.status) {
				case 401:
					store.dispatch('deleteToken')
					store.dispatch('deleteUser')
					location.assign('/login/login.html')
			}
		}
		return Promise.reject(error);
	}
);

new Vue({
	el: '#app',
	router,
	store,
	template: '<App/>',
	components: { App }
})
